"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import Image from "next/image";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { FiUser, FiLock, FiAlertCircle } from "react-icons/fi";
import { SiTencentqq, SiWechat } from "react-icons/si";
import { AiFillDingtalkSquare } from "react-icons/ai";

export default function LoginPage() {
  const router = useRouter();
  const [loginMethod, setLoginMethod] = useState<"password" | "qrcode">(
    "password"
  );
  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("123456");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    try {
      // 模拟登录请求
      await new Promise((resolve) => setTimeout(resolve, 1000));

      if (username === "admin" && password === "123456") {
        // 登录成功
        localStorage.setItem("isLoggedIn", "true");
        toast("登录成功");
        setTimeout(() => {
          router.push("/");
        }, 1000);
      } else {
        setError("用户名或密码错误");
      }
    } catch (err) {
      setError("登录失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  const handleSocialLogin = (platform: string) => {
    setLoading(true);
    localStorage.setItem("isLoggedIn", "true");
    toast("登录成功");
    // 模拟第三方登录
    setTimeout(() => {
      router.push("/");
    }, 1000);
  };

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  return (
    <div className='min-h-screen w-full flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800'>
      <motion.div
        className='w-full max-w-md px-4'
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5 }}
      >
        <div className='text-center mb-8'>
          <h1 className='text-3xl font-bold bg-gradient-to-r from-blue-500 to-purple-600 text-transparent bg-clip-text'>
            雅典娜知识库
          </h1>
          <p className='text-gray-600 dark:text-gray-300 mt-2'>
            企业级知识管理系统
          </p>
        </div>

        <Card className='border-none shadow-xl bg-white/90 dark:bg-gray-800/90 backdrop-blur-sm'>
          <CardHeader>
            <CardTitle className='text-xl text-center'>用户登录</CardTitle>
            <CardDescription className='text-center'>
              请选择登录方式继续访问系统
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue='password' className='w-full'>
              <TabsList className='grid grid-cols-2 mb-6'>
                <TabsTrigger
                  value='password'
                  onClick={() => setLoginMethod("password")}
                >
                  账号密码登录
                </TabsTrigger>
                <TabsTrigger
                  value='qrcode'
                  onClick={() => setLoginMethod("qrcode")}
                >
                  扫码登录
                </TabsTrigger>
              </TabsList>

              <TabsContent value='password'>
                <form onSubmit={handleLogin}>
                  <div className='space-y-4'>
                    <div className='space-y-2'>
                      <Label htmlFor='username'>用户名</Label>
                      <div className='relative'>
                        <FiUser className='absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500' />
                        <Input
                          id='username'
                          placeholder='请输入用户名'
                          value={username}
                          onChange={(e) => setUsername(e.target.value)}
                          className='pl-10'
                          required
                        />
                      </div>
                    </div>

                    <div className='space-y-2'>
                      <Label htmlFor='password'>密码</Label>
                      <div className='relative'>
                        <FiLock className='absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500' />
                        <Input
                          id='password'
                          type='password'
                          placeholder='请输入密码'
                          value={password}
                          onChange={(e) => setPassword(e.target.value)}
                          className='pl-10'
                          required
                        />
                      </div>
                    </div>

                    {error && (
                      <div className='text-red-500 text-sm flex items-center gap-1'>
                        <FiAlertCircle />
                        <span>{error}</span>
                      </div>
                    )}

                    <Button type='submit' className='w-full' disabled={loading}>
                      {loading ? "登录中..." : "登录"}
                    </Button>
                  </div>
                </form>
              </TabsContent>

              <TabsContent value='qrcode'>
                <div className='flex flex-col items-center justify-center py-4'>
                  <div className='bg-white p-3 rounded-lg mb-4 border-2 border-blue-100'>
                    <div className='w-48 h-48 bg-gray-100 relative flex items-center justify-center'>
                      <Image
                        src='/qrcode-placeholder.png'
                        alt='登录二维码'
                        width={180}
                        height={180}
                        className='object-cover'
                        unoptimized
                        onError={(e) => {
                          e.currentTarget.src =
                            "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180' viewBox='0 0 180 180'%3E%3Crect width='180' height='180' fill='%23f5f5f5'/%3E%3Ctext x='90' y='90' font-family='Arial' font-size='12' fill='%23999' text-anchor='middle' dominant-baseline='middle'%3E扫码登录%3C/text%3E%3C/svg%3E";
                        }}
                      />
                    </div>
                  </div>
                  <p className='text-sm text-gray-500 dark:text-gray-400'>
                    请使用对应 App 扫描二维码登录
                  </p>
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>

          <CardFooter className='flex flex-col'>
            <div className='relative w-full mb-4'>
              <div className='absolute inset-0 flex items-center'>
                <div className='w-full border-t border-gray-200 dark:border-gray-700'></div>
              </div>
              <div className='relative flex justify-center text-xs uppercase'>
                <span className='bg-white dark:bg-gray-800 px-2 text-gray-500 dark:text-gray-400'>
                  社交账号登录
                </span>
              </div>
            </div>

            <div className='flex justify-center space-x-6'>
              <Button
                variant='outline'
                size='icon'
                className='rounded-full h-10 w-10 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100'
                onClick={() => handleSocialLogin("dingtalk")}
              >
                <AiFillDingtalkSquare className='h-5 w-5' />
                <span className='sr-only'>钉钉登录</span>
              </Button>

              <Button
                variant='outline'
                size='icon'
                className='rounded-full h-10 w-10 bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-100'
                onClick={() => handleSocialLogin("wechat")}
              >
                <SiWechat className='h-5 w-5' />
                <span className='sr-only'>微信登录</span>
              </Button>

              <Button
                variant='outline'
                size='icon'
                className='rounded-full h-10 w-10 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100'
                onClick={() => handleSocialLogin("qq")}
              >
                <SiTencentqq className='h-5 w-5' />
                <span className='sr-only'>QQ登录</span>
              </Button>
            </div>
          </CardFooter>
        </Card>

        <p className='text-center text-gray-500 dark:text-gray-400 text-sm mt-8'>
          © 2023 雅典娜知识库 版权所有
        </p>
      </motion.div>
    </div>
  );
}
